# Simple PowerShell script to fix database permissions
Write-Host "=== Database Permission Fix ===" -ForegroundColor Green
Write-Host "Start time: $(Get-Date)" -ForegroundColor Yellow

$dataPath = ".\data"
$dbFiles = @(
    "$dataPath\endo_sight_uc.db",
    "$dataPath\endo_sight_uc.db-shm",
    "$dataPath\endo_sight_uc.db-wal"
)

# Check database files
Write-Host "Checking database files..." -ForegroundColor Cyan
foreach ($file in $dbFiles) {
    if (Test-Path $file) {
        Write-Host "Found: $file" -ForegroundColor Green

        # Get current permissions
        $acl = Get-Acl $file
        Write-Host "Current permissions:" -ForegroundColor Yellow
        $acl.Access | ForEach-Object {
            Write-Host "  $($_.IdentityReference.Value): $($_.FileSystemRights)" -ForegroundColor Gray
        }
    }
}

# Remove unnecessary permissions
Write-Host "`nRemoving unnecessary permissions..." -ForegroundColor Cyan
foreach ($file in $dbFiles) {
    if (Test-Path $file) {
        $acl = Get-Acl $file

        # Remove Users group access
        $usersRule = $acl.Access | Where-Object { $_.IdentityReference.Value -eq "BUILTIN\Users" }
        if ($usersRule) {
            $acl.RemoveAccessRule($usersRule) | Out-Null
            Write-Host "Removed Users group: $file" -ForegroundColor Green
        }

        # Remove Authenticated Users access
        $authUsersRule = $acl.Access | Where-Object { $_.IdentityReference.Value -eq "NT AUTHORITY\Authenticated Users" }
        if ($authUsersRule) {
            $acl.RemoveAccessRule($authUsersRule) | Out-Null
            Write-Host "Removed Authenticated Users: $file" -ForegroundColor Green
        }

        # Apply new permissions
        Set-Acl $file $acl
        Write-Host "Updated permissions: $file" -ForegroundColor Green
    }
}

# Set directory permissions
Write-Host "`nSetting data directory permissions..." -ForegroundColor Cyan
if (Test-Path $dataPath) {
    $dirAcl = Get-Acl $dataPath
    $dirAcl.SetAccessRuleProtection($true, $false) | Out-Null
    Set-Acl $dataPath $dirAcl
    Write-Host "Data directory permissions set" -ForegroundColor Green
}

# Verify results
Write-Host "`nVerifying permission fixes..." -ForegroundColor Cyan
foreach ($file in $dbFiles) {
    if (Test-Path $file) {
        $acl = Get-Acl $file
        Write-Host "File: $file" -ForegroundColor Yellow
        $acl.Access | ForEach-Object {
            Write-Host "  $($_.IdentityReference.Value): $($_.FileSystemRights)" -ForegroundColor Green
        }
    }
}

Write-Host "`n=== Database Permission Fix Complete ===" -ForegroundColor Green
Write-Host "End time: $(Get-Date)" -ForegroundColor Yellow
Write-Host "Recommendation: Restart the application" -ForegroundColor Magenta